import os
from datetime import datetime
from tkinter import *
from tkinter.ttk import *
import time
import pandas
import numpy as np
from docx import Document  # 用来建立一个word对象
from docx.shared import Pt  # 用来设置字体的大小
from docx.shared import Inches
from docx.oxml.ns import qn  # 设置字体
from docx.shared import RGBColor  # 设置字体的颜色
from docx.enum.text import WD_ALIGN_PARAGRAPH  # 设置对其方式

path = './毕业生数据.xlsx'
now_date = time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_mday


class WinGUI(Tk):
    data = []

    def __init__(self):
        super().__init__()
        self.__win()
        self.tk_input_lahqj76v = self.__tk_input_lahqj76v()
        self.tk_button_lahqjiqr = self.__tk_button_lahqjiqr()
        self.tk_button_clearTreeView = self.__tk_button_clearTreeView()
        self.tk_label_lahqjroa = self.__tk_label_lahqjroa()
        self.tk_table_lahql409 = self.__tk_table_lahql409()
        self.tk_button_lahqypg6 = self.__tk_button_lahqypg6()
        self.tk_text_lahr58z6 = self.__tk_text_lahr58z6()
        self.tk_button_lahrjpwk = self.__tk_button_lahrjpwk()
        self.tk_label_lahrujr7 = self.__tk_label_lahrujr7()
        self.tk_label_lahrvakm = self.__tk_label_lahrvakm()

    def __win(self):
        self.title("学位授予信息查询、证明打印工具")
        # 设置窗口大小、居中
        width = 1000
        height = 400
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        self.geometry(geometry)
        self.resizable(width=False, height=False)

    def __tk_input_lahqj76v(self):
        ipt = Entry(self)
        ipt.place(x=400, y=20, width=150, height=24)
        return ipt

    def __tk_button_lahqjiqr(self):
        btn = Button(self, text="查询")
        btn.place(x=580, y=20, width=50, height=24)
        return btn

    def __tk_button_clearTreeView(self):
        btn = Button(self, text="清除查询")
        btn.place(x=640, y=20, width=80, height=24)
        return btn

    def __tk_label_lahqjroa(self):
        label = Label(self, text="请输入学号")
        label.place(x=290, y=20, width=85, height=24)
        return label

    def __tk_table_lahql409(self):
        # 表头字段 表头宽度
        columns = {"姓名": 48, "性别": 30, "身份证号": 130, "专业": 120, "毕业证编号": 130, "校长": 48,
                   "学位证编号": 120,
                   "学评委主席": 76, "学位": 57, "入学时间": 80, "毕业时间": 80}
        # 初始化表格 表格是基于Treeview，tkinter本身没有表格。show="headings" 为隐藏首列。
        tk_table = Treeview(self, show="headings", columns=list(columns))
        for text, width in columns.items():  # 批量设置列属性
            tk_table.heading(text, text=text, anchor='center')
            tk_table.column(text, anchor='center', width=width, stretch=True)  # stretch 不自动拉伸

        # 插入数据示例
        # data = [
        #     [1, "github", "https://github.com/iamxcd/tkinter-helper"],
        #     [2, "演示地址", "https://www.pytk.net/tkinter-helper"]
        # ]
        #
        # # 导入初始数据
        # print("self.data", self.data)
        # dataset = []
        # for values in dataset:
        #     tk_table.insert('', END, values=values)

        tk_table.place(x=20, y=90, width=960, height=110)
        return tk_table

    def refresh(self):
        print('refresh', self)

    def __tk_button_lahqypg6(self):
        btn = Button(self, text="生成学位授予证明")
        btn.place(x=790, y=290, width=120, height=50)
        return btn

    def __tk_text_lahr58z6(self):
        text = Text(self)
        text.place(x=20, y=240, width=401, height=145)
        return text

    def __tk_button_lahrjpwk(self):
        btn = Button(self, text="检查数据源")
        btn.place(x=440, y=300, width=95, height=41)
        return btn

    def __tk_label_lahrujr7(self):
        label = Label(self, text="处理日志")
        label.place(x=20, y=210, width=50, height=24)
        return label

    def __tk_label_lahrvakm(self):
        label = Label(self, text="查询信息")
        label.place(x=20, y=60, width=50, height=24)
        return label


class Win(WinGUI):
    def __init__(self):
        super().__init__()
        self.__event_bind()

    def getInputValue(self, evt):
        print("<Button>事件，查询学生{}{}".format(self.tk_input_lahqj76v.get(), evt))
        #  获取输入
        self.findStuByNum(self.tk_input_lahqj76v.get())

    def clearTreeView(self, evt):
        print("清除")
        x = self.tk_table_lahql409.get_children()
        for item in x:
            self.tk_table_lahql409.delete(item)

    def findStuByNum(self, number):

        try:
            studentInfo = pandas.read_excel(path).loc[
                pandas.read_excel(path)['xh'] == int(number), ['xm', 'xb', 'sfzh', 'zymc', 'byzbh', 'xzxm', 'xwzsbh',
                                                               'xwsydwxzxm', 'zylb', 'rxrq',
                                                               'byrq']]
            if len(studentInfo) > 0:
                data_list = np.array(studentInfo).tolist()
                for values in data_list:
                    self.tk_table_lahql409.insert('', END, values=values)
            else:
                showLog("查无此人")
        except Exception as e:
            print('错误')
            showLog(e)

    def exportCertificateFile(self, evt):
        print("<Button>打印事件", evt)
        try:
            format_date = "{}年{}月{}日".format(now_date[0], now_date[1], now_date[2])
            item_text = ()
            for item in self.tk_table_lahql409.selection():
                item_text = self.tk_table_lahql409.item(item, "values")
            print(format_date)
            rxrq = datetime.strptime(str(item_text[9]), '%Y%m').date()
            byrq = datetime.strptime(str(item_text[10]), '%Y%m').date()
            rxrq = "{}年{}月".format(rxrq.year, rxrq.month)
            byrq = "{}年{}月".format(byrq.year, byrq.month)

            cer = ('{}，{}，身份证号：{}，{} 至 {} 在我院 {} 专业完成了本科'
                   '学习计划，成绩合格，准予毕业。经审核符合《中华人民共和国学位条例》和《中南林业科技大学涉外学院学士学位授予管理规定》的规定，授予 {} 学士学位，证书编号：{}。'.format(
                item_text[0], item_text[1], item_text[2], rxrq, byrq, item_text[3], item_text[8],
                item_text[6]))
            print(cer)
            outputFiles(cer)
        except Exception as e:
            print(e)

    def checkDataSource(self, evt):
        print("<Button>事件未处理", evt)

    def __event_bind(self):
        self.tk_button_lahqjiqr.bind('<Button>', self.getInputValue)
        self.tk_button_lahqypg6.bind('<Button>', self.exportCertificateFile)
        self.tk_button_lahrjpwk.bind('<Button>', self.checkDataSource)
        self.tk_button_clearTreeView.bind('<Button>', self.clearTreeView)


def outputFiles(data):
    print("输出文件", data)

    # 创建一个空白的word文档
    doc = Document()

    # 设置1级标题
    para_heading = doc.add_heading('', level=1)  # 返回1级标题段落对象，标题也相当于一个段落
    para_heading.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 设置为左对齐
    para_heading.paragraph_format.space_before = Pt(0)  # 设置段前 0 磅
    para_heading.paragraph_format.space_after = Pt(0)  # 设置段后 0 磅
    para_heading.paragraph_format.line_spacing = 1.5  # 设置行间距为 1.5
    para_heading.paragraph_format.left_indent = Inches(0)  # 设置左缩进 1英寸
    para_heading.paragraph_format.right_indent = Inches(0)  # 设置右缩进 0.5 英寸

    run = para_heading.add_run(u"学士学位授予证明")
    run.font.name = u'华文中宋'  # 设置为宋体
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'华文中宋')  # 设置为宋体，和上边的一起使用
    run.font.size = Pt(26)  # 设置1级标题文字的大小为“小四” 为12磅
    run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
    doc.add_paragraph()
    # 增加一段文字
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(0)  # 设置段前 0 磅
    p.paragraph_format.space_after = Pt(0)  # 设置段后 0 磅
    p.paragraph_format.line_spacing = 1.5  # 设置行间距为 1.5倍
    p.paragraph_format.first_line_indent = Inches(0.5)  # 段落首行缩进为 0.5英寸

    p.paragraph_format.left_indent = Inches(0)  # 设置左缩进 1英寸
    p.paragraph_format.right_indent = Inches(0)  # 设置右缩进 0.5 英寸

    r = p.add_run(data)
    r.font.name = u'宋体'  # 设置为宋体
    r._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')  # 设置为宋体，和上边的一起使用
    r.font.size = Pt(16)  # 设置字体大小为12磅 相当于 小四
    r.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
    doc.save("./证明文件/{}.docx".format('20170350'))


def showLog(info):
    print(info)


def checkDataSource():
    if os.path.exists(path):
        showLog("文件存在")
    else:
        showLog("文件不存在")


if __name__ == "__main__":
    win = Win()
    checkDataSource()
    win.mainloop()
